<template>
  <div class="box">
    <div class="card-container">
      <el-row :gutter="10">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
          <el-col :span="19" :offset="0">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker v-model="queryParams.createTime" type="datetimerange" style="width: 320px"
                range-separator="至" start-placeholder="开始日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="震中地名" prop="locname">
              <el-input v-model="queryParams.locname" placeholder="请输入震中地名" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="信息类型" prop="msgType">
              <el-radio-group v-model="queryParams.msgType">
                <el-radio :key="'0'" :label="'0'">全部</el-radio>
                <el-radio v-for="dict in dict.type.sys_event_type" :key="dict.value" :label="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="0">
            <el-form-item>
              <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </div>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button   icon="el-icon-plus" size="mini" v-hasPermi="['drill:add']"
          @click="handleAdd">新增演练</el-button>
        <el-button   icon="el-icon-delete" size="mini" :disabled="multiple" v-show="!multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
    </el-row> -->
    <div class="card-container">
      <div class="body-title">
        <div class="body-title-left">预警演练</div>
        <div class="body-title-right">
          <!-- <el-button   v-hasPermi="['drill:add']" @click="handleAdd">新增演练
          </el-button> -->
          <el-button icon="el-icon-plus" size="mini" v-hasPermi="['drill:add']" @click="handleAdd">新增演练</el-button>
          <el-button icon="el-icon-delete" size="mini" :disabled="multiple" v-show="!multiple"
            @click="handleDelete">删除</el-button>
        </div>
      </div>

      <el-table :data="tableData" v-loading="loading" height="500" :row-key="getRowKey" :row-class-name="getRowClass"
        style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
        <el-table-column prop="createTime" align="center" show-overflow-tooltip label="创建时间" width="240">
        </el-table-column>
        <el-table-column prop="msgType" align="center" show-overflow-tooltip label="信息类型">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_event_type" :value="scope.row.msgType" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="演练地震事件信息" width="360">
          <template slot-scope="scope">
            <div class="eewMessage">
              <div>
                <div style="flex: 1">震级：</div>
                <div style="flex: 6">{{ scope.row.magnitude || "--" }}级</div>
              </div>
              <div>
                <div style="flex: 1">烈度：</div>
                <div style="flex: 6">{{ scope.row.epiintensity || "--" }}°</div>
              </div>
              <div>
                <div style="flex: 1">深度：</div>
                <div style="flex: 6">{{ scope.row.focdepth || "--" }}km</div>
              </div>
              <div>
                <div style="flex: 1">经度：</div>
                <div style="flex: 6">{{ scope.row.epilon || "--" }}°</div>
              </div>
              <div>
                <div style="flex: 1">纬度：</div>
                <div style="flex: 6">{{ scope.row.epilat || "--" }}°</div>
              </div>
              <div>
                <div style="flex: 1">地名：</div>
                <div style="flex: 6">{{ scope.row.locname || "--" }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="信息接收对象" width="400" prop="drillProjectVOS">
          <template slot-scope="scope">
            <el-tree :data="scope.row.drillProjectVOS" :style="`height:150px;overflow-y: auto;`" default-expand-all>
              <span class="custom-tree-node" slot-scope="{data}">
                <span
                  :style="{ '--inputColor': !data.onlineStatus ? '' : data.onlineStatus == '1' ? '#67C23A' : '#F56C6C' }">{{
                    data.name }}</span>
              </span>
            </el-tree>
          </template>
        </el-table-column>
        <el-table-column align="center" label="推送次数" prop="pushCount">
        </el-table-column>
        <el-table-column prop="updateBy" align="center" label="操作人">
        </el-table-column>
        <!-- fixed="right" -->
        <el-table-column align="center" min-width="150" label="操作">
          <template slot-scope="scope">
            <el-button type="text" v-hasPermi="['drill:query']" v-if="scope.row.pushCount > 0"
              @click="handleEdit(scope.row, '详情')">
              详情
            </el-button>
            <el-button type="text" v-hasPermi="['drill:edit']" v-else @click="handleEdit(scope.row, '编辑')">
              编辑
            </el-button>
            <!-- <el-button type="text" v-hasPermi="['drill:remove']" @click="handleDelete(scope.row)">
              删除
            </el-button> -->
            <el-button type="text" :disabled="!scope.row.onlineStatus" v-hasPermi="['drillPushTotalLog:add']"
              @click="handlePush(scope.row)">推送
            </el-button>
            <el-button type="text" v-hasPermi="['drillPushTotalLog:query']" :disabled="scope.row.pushCount <= 0"
              @click="handleLog(scope.row)">
              记录</el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <el-dialog :title="title" :show-close="true" :close-on-click-modal="false" v-if="dialogVisible"
      :visible.sync="dialogVisible" width="50%">
      <template #title>
        <div style="display: flex; justify-content: space-between;color:#fff">
          <span>{{ title }}</span>
          <!-- <el-button v-if="title == '新增'"   size="mini" @click="history">历史事件模板
          </el-button> -->
        </div>
      </template>
      <div class="dialogBox">
        <div class="card-container">
          <el-row :gutter="10">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-col :span="24" :offset="0">
                <el-form-item label="信息类型" required prop="msgType">
                  <el-radio-group v-model="form.msgType" :disabled="isTitle">
                    <el-radio v-for="dict in dict.type.sys_event_type" v-show="dict.label !== '正式'" :key="dict.value"
                      :label="dict.value">{{ dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="震级(M)" prop="magnitude">
                  <!-- <limit-input v-model="form.magnitude" :disabled="isTitle" :placeholder="'请输入震级'" /> -->
                  <el-input v-model="form.magnitude" :disabled="isTitle"
                    oninput="value=value.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3')" :placeholder="'请输入震级'">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="震源深度(km)" prop="focdepth">
                  <!-- <limit-input v-model="form.focdepth" :disabled="isTitle" :placeholder="'请输入深度'" /> -->
                  <el-input v-model="form.focdepth" :disabled="isTitle" oninput="value=value.replace(/[^0-9]/g,'')"
                    :placeholder="'请输入深度'">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="震中烈度(°)" prop="epiintensity">
                  <el-input v-model="form.epiintensity" disabled> </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="经度(°)" prop="epilon">
                  <limit-input v-model="form.epilon" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item label="纬度(°)" prop="epilat">
                  <limit-input v-model="form.epilat" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-col :span="19" :offset="0">
                  <el-form-item label="预警配置" prop="levelConfigName">
                    <el-select style="width:100%" :disabled="isTitle" v-model="form.levelConfigName"
                      @change="changLevel(form.levelConfigName)" placeholder="请选择预警配置">
                      <el-option v-for="item in warmList" :key="item.name" :label="item.name"
                        :value="item.name == '自动规则' ? '' : item.name">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4" :offset="0">
                  <el-button size="small" @click="handleLook">查看</el-button>
                </el-col>

              </el-col>
              <!-- <el-col :span="2" :offset="0">
             
            </el-col> -->
            </el-form>
          </el-row>
        </div>
        <div class="card-container">
          <div class="title">
            <div>
              信息接收对象 (已选
              <span style="color: #409eff">{{ objectData.length }}</span> 个)
            </div>
            <el-button type="text" icon="el-icon-plus" :disabled="isTitle" @click="objectAdd">新增
            </el-button>
          </div>
          <div style="padding: 20px 20px">
            <el-table default-expand-all :data="objectData" :key="isUpdate" :height="maxHeight" style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-table :data="scope.row.obj" style="width: 100%">
                    <el-table-column prop="level" align="center" show-overflow-tooltip label="预警等级" min-width="150">
                      <template slot-scope="scope">
                        <span>{{ lvTwo(
                          scope.row.level) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="localIntensity" align="center" show-overflow-tooltip label="本地烈度(°)"
                      min-width="80">
                      <!-- <template slot-scope="scope">
                      <span> {{ scope.row.localIntensity }}</span>
                    </template> -->
                    </el-table-column>
                    <el-table-column prop="distance" align="center" show-overflow-tooltip label="震中距(km)" min-width="80">
                      <!-- <template slot-scope="scope">
                      <span>{{scope.row.distance }}</span>
                    </template> -->
                    </el-table-column>
                    <el-table-column prop="localWarningTime" align="center" show-overflow-tooltip label="预警倒计时(s)"
                      min-width="80">
                      <!-- <template slot-scope="scope">
                      <span> {{scope.row.localWarningTime}}</span>
                    </template> -->
                    </el-table-column>
                  </el-table>
                </template>
              </el-table-column>
              <el-table-column prop="projectName" align="center" show-overflow-tooltip label="项目名称">
              </el-table-column>
              <el-table-column prop="siteName" align="center" show-overflow-tooltip label="站点名称">
              </el-table-column>
              <el-table-column prop="code" align="center" show-overflow-tooltip width="280" label="设备序列号">
              </el-table-column>
              <el-table-column prop="deviceType" align="center" show-overflow-tooltip label="设备类型">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_device_mode" :value="scope.row.deviceType" />
                </template>
              </el-table-column>
              <el-table-column prop="onlineStatus" align="center" show-overflow-tooltip label="在线状态">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_on_line_status" :value="scope.row.onlineStatus" />
                </template>
              </el-table-column>
              <el-table-column align="center" show-overflow-tooltip label="操作">
                <template slot-scope="scope">
                  <el-button type="text" :disabled="isTitle" @click="remove(scope.row)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div class="card-container">
          <div class="title">
            <div>设置事件位置</div>
            <div>
            </div>
          </div>
          <div style="padding: 20px 20px">
            <Map ref="map" :title="title" :topForm="form" :device="objectData" @getForm="updateLocation"
              :oneGrad="+oneGrad" :twoGrad="+twoGrad" :threeGrad="+threeGrad" :fourGrad="+fourGrad" />
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handlerCancel">取 消</el-button>
        <el-button @click="handlerSubmit(null)" :disabled="objectData.length <= 0" v-if="!isTitle">仅保存</el-button>
        <el-button v-hasPermi="['drillPushTotalLog:add']" :disabled="objectData.length <= 0" @click="handleSubmit"
          v-if="!isTitle">保存并推送</el-button>
        <!-- <el-button  @click="handlePush" v-if="title == '推送'">推送</el-button> -->
      </div>
    </el-dialog>

    <el-dialog title="选择接收对象" :close-on-click-modal="false" :visible.sync="objectVisible" width="50%">
      <div class="card-container">
        <el-row :gutter="20">
          <el-form :model="objectQuery" ref="objectQuery" :inline="true" label-width="80px">
            <el-col :span="20" :offset="0">
              <el-form-item label="序列号" prop="code">
                <el-input v-model="objectQuery.code" placeholder="请输入序列号" clearable
                  @keyup.enter.native="handleObjectQuery" />
              </el-form-item>
              <el-form-item label="项目名称" prop="shortName">
                <el-select v-model="objectQuery.shortName" clearable :style="'width:215px'" placeholder="请选择项目">
                  <el-option v-for="item in projectList" :key="item.projectId" :label="item.shortName"
                    :value="item.shortName">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="设备类型" prop="deviceType">
                <el-select v-model="objectQuery.deviceType" clearable placeholder="请选择设备类型">
                  <el-option v-for="dict in this.dict.type.sys_device_mode" :key="dict.value" :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="在线状态" prop="onlineStatus">
                <el-select v-model="objectQuery.onlineStatus" clearable placeholder="请选择在线状态">
                  <el-option v-for="dict in dict.type.sys_on_line_status" :key="dict.value" :label="dict.label"
                    :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="设备型号" prop="modelId">
                <el-select v-model="objectQuery.modelId" clearable placeholder="请选择设备型号">
                  <el-option v-for="item in modList" :key="item.modelId" :label="item.model" :value="item.modelId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" :offset="0">
              <el-form-item>
                <el-button icon="el-icon-search" size="mini" @click="handleObjectQuery">搜索
                </el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>

      <div class="card-container">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="预警终端" style="height: 400px" name="receive">
            <el-table :data="receiveData" ref="receive" height="300" :row-key="getRowKeys" @selection-change="select"
              style="width: 100%">
              <el-table-column type="selection" align="center" :reserve-selection="true" width="55">
              </el-table-column>
              <el-table-column prop="projectName" align="center" show-overflow-tooltip label="项目名称">
              </el-table-column>
              <el-table-column prop="siteName" align="center" show-overflow-tooltip label="站点名称">
              </el-table-column>
              <el-table-column prop="code" align="center" show-overflow-tooltip label="设备序列号">
              </el-table-column>
              <el-table-column prop="modelId" align="center" show-overflow-tooltip label="设备型号">
                <template slot-scope="scope">
                  <span>{{ handleMode(scope.row.modelId) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="deviceTypeLabel" align="center" show-overflow-tooltip label="设备类型">
                <!-- <template slot-scope="scope"> handleMode
                <dict-tag v-if="scope.row.type == 2" :options='dict.type.sys_publish_client_type'
                  :value='scope.row.clientType' />
                <dict-tag v-else :options='dict.type.sys_receive_client_type'
                  :value='scope.row.clientType' /> 
              </template> -->
              </el-table-column>
              <el-table-column prop="onlineStatus" align="center" show-overflow-tooltip label="在线状态">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_on_line_status" :value="scope.row.onlineStatus" />
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="receiveTotal > 0" :total="receiveTotal" :page.sync="objectQuery.pageNum"
              :limit.sync="objectQuery.pageSize" @pagination="getObject" />
          </el-tab-pane>
        </el-tabs>

      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handlerObjectSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预警规则 -->
    <el-dialog :visible.sync="outerVisible" center append-to-body>
      <el-table :data="warmLevlData" style="width: 100%;">
        <el-table-column prop="intensity" align="center" show-overflow-tooltip label="烈度范围" min-width="150">
          <template slot-scope="scope">
            <el-tag v-for="(item, index) in scope.row.intensity" :key="index" :color="formatColor(scope.row.level)"
              effect="dark">{{ item }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" align="center" show-overflow-tooltip label="预警等级" min-width="80">
        </el-table-column>
        <el-table-column prop="levelColor" align="center" show-overflow-tooltip label="等级颜色" min-width="80">
        </el-table-column>
        <el-table-column prop="guidance" align="center" show-overflow-tooltip label="避震指导" min-width="80">
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 推送进度 -->
    <el-dialog :title="'推送进度'" :close-on-click-modal="false" :before-close="pushClose" v-if="pushScheduleOpen"
      :visible.sync="pushScheduleOpen" width="800px" append-to-body>
      <push-schedule @close="pushClose" :row="pushScheduleList" />
    </el-dialog>
    <!-- 推送记录 -->
    <el-dialog :title="'推送记录'" :close-on-click-modal="false" v-if="updateLogOpen" :visible.sync="updateLogOpen"
      width="800px" append-to-body>
      <update-log :row="updateList" @handleCheck="handleCheck" />
    </el-dialog>
    <!-- 升级失败设备列表 -->
    <el-dialog :title="failTitle" :close-on-click-modal="false" v-if="updateFailOpen" :visible.sync="updateFailOpen"
      width="1000px" append-to-body>
      <update-fail :row="updateFailList" />
    </el-dialog>

  </div>
</template>

<script>
import {
  getList,
  handleAdd,
  getDetails,
  getDevice,
  getPushIndex,
  handleDelete,
  handleEdit,
  getLevel,
  saveLevel,
  warningCountdown,
  getDefaultConfig
} from "@/api/rehearsal/index.js";
import { listLevelWarm, getLevelWarm } from '@/api/configuration/alertLevel/index.js'
import limitInput from "@/components/limitInput/index.vue";
import { getProject } from "@/api/runningLog/runningLog.js";
import Map from "@/components/Map_1/index";
import pushSchedule from "./pushSchedule.vue";
import updateLog from "./updateLog.vue";
import updateFail from "./updateFail.vue";
export default {
  name: "rehearsal",
  dicts: [
    "earthquake_level",
    "sys_push_state",
    "sys_event_type",
    "sys_on_line_status",
    "sys_device_mode",
  ],
  components: {
    limitInput,
    Map,
    pushSchedule,
    updateLog,
    updateFail,
  },
  data() {
    const _this = this;
    return {
      warmList: [],//预警配置列表
      warmLevlData: [],
      outerVisible: false,
      updateFailOpen: false,
      failTitle: "演练推送失败设备列表",
      updateFailList: {},
      updateList: {},
      updateLogOpen: false,
      pushScheduleList: {
        row: {},
        drillPushTotalId: null,
      },
      isUpdate: false,
      pushScheduleOpen: false,
      isEdit: false,
      configId: "",
      gridDataCopy: "",
      times: null,
      modList: [],
      projectList: [],
      publishData: [],
      publishTotal: 0,
      receiveTotal: 0,
      receiveData: [],
      options: [],
      msgId: [],
      activeName: "receive",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        locname: null,
        createTime: [],
        msgType: "0",
      },
      form: {
        epilon: null,
        epilat: null,
        locname: null,
        deviceId: [],
        msgType: "2",
        // addressList: [],
        epiintensity: 0,
        magnitude: 0,
        levelConfigName: '',
      },
      tableData: [],
      total: 0,
      date: [],
      title: "",
      oneGrad: null,
      twoGrad: null,
      threeGrad: null,
      fourGrad: null,
      dialogVisible: false,
      objectVisible: false,
      rules: {
        magnitude: [
          { required: true, message: "震级不能为空", trigger: "blur" },
        ],
        oritimes: [
          { required: true, message: "发震时间不能为空", trigger: "change" },
        ],
        focdepth: [
          { required: true, message: "深度不能为空", trigger: "blur" },
        ],
        // levelConfigName: [{
        //   required: true, message: '预警配置不能为空', trigger: 'change'
        // }],
        locname: [
          { required: true, message: "震中地名不能为空", trigger: "blur" },
        ],
        epilon: [{ required: true, message: "经度不能为空", trigger: "blur" }],
        epilat: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
        sendTime: [
          {
            required: true,
            message: "演练发布时间不能为空",
            trigger: "change",
          },
        ],
      },
      multiple: true,
      objectQuery: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        shortName: null,
        deviceType: null,
        onlineStatus: null,
        modelId: null,
      },
      isPromptly: false,
      oritimes: null,
      objectData: [],
      publishIds: [],
      receiveIds: [],
      loading: false
    };
  },
  computed: {},
  async created() {
    this.listLevelWarm()
  },
  mounted() {
    this.getConfig();
    this.getList();
  },
  computed: {
    isTitle() {
      if (this.title == "新增" || this.title == "编辑") {
        return false;
      } else {
        return true;
      }
    },
    maxHeight() {
      if (this.objectData.length > 4) {
        return "400";
      } else if (this.objectData.length >= 2 && this.objectData.length < 4) {
        return "300";
      } else {
        return "200";
      }
    },
  },
  watch: {
    activeName(val) {
      this.$nextTick(() => {
        this.$refs[val].doLayout();
      });
    },
    objectVisible() {
      this.activeName = "receive";
    },
    "form.magnitude"() {
      if (this.form.magnitude > 12) {
        this.form.magnitude = 12;
      } else if (this.form.magnitude < 0) {
        this.form.magnitude = 0;
      }
      this.form.epiintensity = Math.round((this.form.magnitude * 1.29 + 0.24));
      // if (this.form.magnitude <= 1.5) {
      //   this.form.epiintensity = 0;
      // } else {
      //   this.form.epiintensity = Math.round((this.form.magnitude - 1.5) / 0.58);
      // }
      if (this.title == "新增") {
        this.warningCountdown()
      }
    },
    'form.focdepth'() {
      if (this.form.focdepth) {
        if (this.title == "新增") {
          this.warningCountdown()
        }

      }
    },
  },
  beforeCreate() { },
  beforeMount() { },
  beforeDestroy() { },
  methods: {
    // 倒计时
    warningCountdown() {
      if (this.form.epilat && this.form.epilon && this.form.focdepth && this.objectData.length > 0) {
        this.objectData.forEach(async (item, index) => {
          const res = await warningCountdown({
            epilat: this.form.epilat,// 震源纬度
            epilon: this.form.epilon,//震源经度
            focdepth: Number(this.form.focdepth),//震源深度
            Epiintensity: this.form.epiintensity,//震源烈度
            localLatitude: item.latitude,//本地纬度
            localLongitude: item.longitude,//本地经度
            publishTime: this.format("yyyy-MM-dd HH:mm:ss.S", 0),//当前时间
            oritime: this.format("yyyy-MM-dd HH:mm:ss.S", 300),//发震时间
          })
          if (res.code == 200) {
            this.$nextTick(() => {
              this.$refs.map.mapDraw([this.form.epilon, this.form.epilat])
            })
            item.level = res.data.localIntensity
            item.obj = [{
              level: res.data.localIntensity,
              localIntensity: Math.round(res.data.localIntensity),
              distance: res.data.distance,
              localWarningTime: res.data.localWarningTime
            }]
            this.isUpdate = !this.isUpdate
          }
        })
      }
    },

    // 格式化时间
    format(fmt, Delay) {
      let _date = new Date()
      var o = {
        "M+": _date.getMonth() + 1, //月份
        "d+": _date.getDate(), //日
        "h+": _date.getHours() % 12 == 0 ? 12 : _date.getHours() % 12, //小时
        "H+": _date.getHours(), //小时
        "m+": _date.getMinutes(), //分
        "s+": _date.getSeconds(), //秒
        // "q+": Math.floor((_date.getMonth() + 3) / 3), //季度
        "S": _date.getMilliseconds() + Delay //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (_date.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      return fmt;
    },
    handleLook() {
      this.outerVisible = true
    },
    changLevel(val) {
      console.log(val, this.objectData.length, ' this.getDefaultConfig(this.objectData[0].deviceId)')
      if (val == '') {
        if (this.objectData.length > 0) {
          this.getDefaultConfig(this.objectData[0].deviceId)
        }
        return
      }
      this.warmLevlData = this.warmList.filter(item => {
        return item.name == val
      })[0].levelConfigVOList
      this.oneGrad = this.warmLevlData[0].intensity.slice(-1)[0]
      this.twoGrad = this.warmLevlData[1].intensity.slice(-1)[0]
      this.threeGrad = this.warmLevlData[2].intensity.slice(-1)[0]
      this.fourGrad = this.warmLevlData[3].intensity.slice(-1)[0]

      this.warningCountdown()
    },
    formatColor(val) {
      switch (val) {
        case '无预警':
          return 'grey'
        case 'Ⅳ级':
          return '#409EFF'
        case 'Ⅲ级':
          return 'yellow'
        case 'Ⅱ级':
          return 'orange'
        case 'Ⅰ级':
          return 'red'
        default:
          break;
      }
    },
    formatlevel(val) {
      switch (val) {
        case '无预警':
          return '无预警（灰色）'
        case 'Ⅳ级':
          return '蓝色预警'
        case 'Ⅲ级':
          return '黄色预警'
        case 'Ⅱ级':
          return '橙色预警'
        case 'Ⅰ级':
          return '红色预警'
        default:
          break;
      }
    },
    // 获取预警配置列表
    async listLevelWarm() {
      const res = await listLevelWarm(this.queryParams);
      if (res.code == 200) {
        let obj = {
          name: '自动规则',
        }
        this.warmList = res.rows || []
        this.warmList.forEach(item => {
          item.levelConfigVOList.forEach(list => {
            list.intensity = list.intensity.split(',').map(Number);
          })
        })
        this.warmList.unshift(obj)
      }
    },
    // 查询单条
    async getLevelWarm(name) {
      const res = await getLevelWarm(name);
      if (res.code == 200) {
        if (res.data.length > 0) {
          this.warmLevlData = res.data[0].levelConfigVOList
          this.warmLevlData.forEach(list => {
            list.intensity = list.intensity.split(',').map(Number);
          })
          this.oneGrad = this.warmLevlData[0].intensity.slice(-1)[0]
          this.twoGrad = this.warmLevlData[1].intensity.slice(-1)[0]
          this.threeGrad = this.warmLevlData[2].intensity.slice(-1)[0]
          this.fourGrad = this.warmLevlData[3].intensity.slice(-1)[0]
          console.log(this.oneGrad, this.twoGrad, this.threeGrad, this.fourGrad, 'fourGradfourGradfourGradfourGrad')
        } else {
          this.warmLevlData = []
        }
      }
    },
    getRowKeys(row) {
      return row.deviceId;
    },
    pushClose() {
      this.pushScheduleOpen = false;
      this.handleQuery();
    },
    async handleDelete() {
      this.$modal
        .confirm("是否确认删除当前演练？")
        .then(async () => {
          const res = await handleDelete(this.msgId);
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
            this.handleQuery();
          }
        })
        .catch(() => { });
    },
    handleLog(row) {
      this.updateList = row;
      this.updateLogOpen = true;
    },
    handleCheck(row, sta) {
      this.updateFailList = row;
      if (sta == "0") {
        this.updateFailList.pushStatus = sta;
        this.failTitle = "预警演练推送失败设备列表";
      } else {
        this.updateFailList.pushStatus = "";
        this.failTitle = "预警演练推送设备列表";
      }
      this.updateFailOpen = true;
    },
    mend(val) {
      if (val < 10) {
        return "0" + val;
      } else {
        return val;
      }
    },
    initTime(time) {
      let date = new Date(time);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = date.getDate() + " ";
      let h = date.getHours() + ":";
      let m = date.getMinutes() + ":";
      let s = date.getSeconds();
      return h + m + s;
    },
    select(row) {
      if (this.activeName == "publish") {
        this.publishIds = row;
      } else {
        this.receiveIds = row;
      }
    },
    remove(row) {
      this.objectData = this.objectData.filter((item) => {
        return item.deviceId !== row.deviceId;
      });
    },
    updateLocation(Addr) {
      if (this.title !== "查看") {
        console.log(Addr, 'Addr')
        this.form.epilon = Addr.longitude;
        this.form.epilat = Addr.latitude;
        // this.form.addressList = Addr.addressList;
        this.form.locname = Addr.name;
        this.warningCountdown()
      }
    },
    spot() {
      if (!this.isTitle) {
        this.$refs.map.mapDraw([this.form.epilon, this.form.epilat]);
      }
    },
    getRowKey(row) {
      return row.msgId;
    },
    handleSelectionChange(selection) {
      this.msgId = selection.map((item) => item.msgId);
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.form = {
        epilon: null,
        epilat: null,
        locname: null,
        deviceId: [],
        msgType: "2",
        epiintensity: 0,
        magnitude: 0,
        levelConfigName: '',
        // addressList: [],
      };
      this.title = "新增";
      this.isPromptly = false;
      this.objectData = [];
      this.dialogVisible = true;
    },
    async handleEdit(row, title) {
      this.times && clearTimeout(this.times);
      const res = await getDetails(row.msgId);
      if (res.code == 200) {
        this.title = title;
        // this.form = Object.assign(this.form, res.data);
        this.form = res.data;
        if (this.form.levelConfigName == '') {
          this.getDefaultConfig(this.form.deviceInfo[0].deviceId)
        } else {
          this.getLevelWarm(this.form.levelConfigName)
        }

        // this.getLevelWarm(this.form.levelConfigName)
        this.objectData = res.data.deviceInfo;
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.times = setTimeout(() => {
            this.warningCountdown()
            this.$refs.map.handlePosition(true);
          }, 800);
        });
      }
    },
    async objectAdd() {
      this.objectQuery = {
        pageNum: 1,
        pageSize: 10,
        code: null,
        shortName: null,
        deviceType: null,
        onlineStatus: null,
        modelId: null,
      };
      // this.publishData = [];
      this.receiveData = [];
      // const project = await this.$api.getProject();
      // if (project.code == 200) {
      //   this.options = project.data;
      // }
      this.getObject();
      this.objectVisible = true;
      this.$nextTick(() => {
        this.$refs.receive.clearSelection();
        this.objectData.forEach((item) => {
          this.$refs.receive.toggleRowSelection(item, true);
        });
      });
      // this.$refs.receive.doLayout()
    },
    async getObject() {
      console.log(this.objectQuery, "this.objectQuery");
      const res1 = await getDevice(this.objectQuery);
      if (res1.code == 200) {
        console.log(res1.rows, "this.receiveData");
        this.receiveData = res1.rows;
        this.receiveTotal = res1.total;
        if (this.objectData.length > 0) {
          let data = this.objectData.map((item) => {
            return item.deviceId;
          });
          this.receiveData.forEach((item) => {
            if (data.includes(item.deviceId)) {
              this.$nextTick(() => {
                this.$refs["receive"].toggleRowSelection(item, true);
              });
            }
          });
          // this.$refs['publish'].toggleRowSelection(item, true);
        }
      }
    },
    async getList() {
      this.loading = true
      const res = await getList(this.queryParams);
      if (res.code == 200) {
        this.tableData = res.rows;
        this.tableData.forEach((item, index) => {
          if (item.drillProjectVOS.length > 0) {
            item.drillProjectVOS[0].children.forEach((obj, i) => {
              if (obj.onlineStatus == '1') {
                obj.name = obj.code + '(在线)'
                item.onlineStatus = true
              } else {
                obj.name = obj.code + '(离线)'
                if (!item.onlineStatus) {
                  item.onlineStatus = false
                }
              }
              obj.children[0].name = `    预警等级：${this.formatlevel(obj.children[0].warningLevel)}
       震中距：${obj.children[0].distance}km
    本地烈度：${Math.round(obj.children[0].localIntensity)}°
预警倒计时：${obj.children[0].localWarningTime}s`
            })
          }
        })
        this.total = res.total;
      }
      this.loading = false
    },
    async getConfig() {
      this.modList = await this.$api.getMod();
      const res = await getProject();
      if (res.code == 200) {
        this.projectList = res.data;
      }
    },
    handleMode(type) {
      const facId = this.modList.filter((item) => {
        return item.modelId == type;
      })[0].model;
      return facId;
    },
    handleObjectQuery() {
      this.getObject();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      // this.queryParams.level = [this.level, this.level1];
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.date = [];
      this.handleQuery();
    },
    handleRouter(row) {
      this.$router.push({
        path: "transpondDetails",
        query: { msgId: row.msgId },
      });
    },
    getRowClass(row, rowIndex) {
      if (row.row.normalWarnings) {
        if (row.row.normalWarnings.length === 0) {
          return "row-expand-cover";
        }
      } else {
        return "row-expand-cover";
      }
    },

    // 选择信息接收设备
    handlerObjectSubmit() {
      this.objectData = [];
      if (this.objectData.length > 0) {
        const data = this.publishIds.concat(this.receiveIds);
        this.objectData = this.objectData.concat(data);
      } else {
        this.objectData = this.publishIds.concat(this.receiveIds);
      }
      console.log(this.objectData, this.form.levelConfigName, 'this.')
      if (this.form.levelConfigName == '') {
        this.getDefaultConfig(this.objectData[0].deviceId)
      }
      this.warningCountdown()
      this.objectVisible = false;
    },

    // 查询自动配置
    async getDefaultConfig(id) {
      const res = await getDefaultConfig(id)
      if (res.code == 200) {
        res.data.forEach(item => {
          item.levelConfigVOList.forEach(list => {
            list.intensity = list.intensity.split(',').map(Number);
          })
        })
        this.warmLevlData = res.data[0].levelConfigVOList
        this.oneGrad = this.warmLevlData[0].intensity.slice(-1)[0]
        this.twoGrad = this.warmLevlData[1].intensity.slice(-1)[0]
        this.threeGrad = this.warmLevlData[2].intensity.slice(-1)[0]
        this.fourGrad = this.warmLevlData[3].intensity.slice(-1)[0]
      }
    },
    async handlerSubmit(cb) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.form.deviceId = this.objectData.map((item) => {
            return item.deviceId;
          });
          if (this.form.msgId == null) {
            const res = await handleAdd(this.form);
            if (res.code == 200) {
              this.$modal.msgSuccess(res.msg);
              this.dialogVisible = false;
              this.handleQuery();
              console.log(res, 'res')
              cb && cb(res);
            } else {
              this.$modal.msgError(res.msg);
            }
          } else {
            const res = await handleEdit(this.form);
            if (res.code == 200) {
              this.$modal.msgSuccess(res.msg);
              this.dialogVisible = false;
              this.handleQuery();
              cb && cb(res);
            } else {
              this.$modal.msgError(res.msg);
            }
          }
        }
      });
    },
    async handleSubmit() {
      this.handlerSubmit((res) => {
        this.handlePush(res.data);
      });
    },
    async handlePush(row) {
      if (this.title == "") {
        console.log(row, 'row')
        this.$modal
          .confirm('是否确认推送预警消息？')
          .then(async () => {
            const res = await getPushIndex({ msgId: row.msgId });
            if (res.code == 200) {
              this.pushScheduleList = {
                row,
                drillPushTotalId: res.data,
              };
              this.pushScheduleOpen = true;
            }
          })
          .catch(() => { });
      } else {
        const res = await getPushIndex({ msgId: row.msgId });
        if (res.code == 200) {
          this.pushScheduleList = {
            row,
            drillPushTotalId: res.data,
          };
          this.pushScheduleOpen = true;
        }
      }
    },
    handlerCancel() {
      this.dialogVisible = false;
    },
    history() {
      this.$router.push({
        path: "/message/eventQuery",
      });
    },
    lvTwo(value) {
      let lv = "无预警";
      let _value = Math.round(value)
      if (_value <= this.oneGrad) {
        lv = '无预警';
      } else if (_value > this.oneGrad && _value <= this.twoGrad) {
        lv = '蓝色预警';
      } else if (_value > this.twoGrad && _value <= this.threeGrad) {
        lv = '黄色预警';
      } else if (_value > this.threeGrad && _value <= this.fourGrad) {
        lv = '橙色预警';
      } else if (_value > this.fourGrad) {
        lv = '红色预警';
      }
      return lv;
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
  padding: 20px;
}



.body-title {
  display: flex;
  position: relative;
  // justify-content: space-between;
  align-items: center;
}

.body-title-left {
  height: 100%;
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 600;
  color: #fff;
  line-height: 64px;
}

.body-title-right {
  position: absolute;
  right: 0;
}

.eewMessage {
  >div {
    display: flex;
    text-align: left;
  }
}

.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 20px 0 20px;
  font-weight: 700;
  font-size: 16px;
  color: #fff;
}

.dialogBox {
  height: 648px;
  padding: 0 12px;
  overflow: hidden;
  overflow-y: auto;
}

// ::v-deep .el-tag--medium {
//   width: 40px;
//   height: 28px;
//   line-height: 28px;
//   margin-right: 10px;
//   text-align: center;
// }

::v-deep .custom-tree-node {
  >span {
    color: var(--inputColor);
  }
}

::v-deep .el-tree-node__content {
  white-space: pre-wrap;
  text-align: left;
  height: 100%;
}

::v-deep .el-tree-node__content:hover,
.el-upload-list__item:hover {
  background: rgba(255, 255, 255, 0.3);
  color: #0095ff;
}

::v-deep .el-tree-node:focus>.el-tree-node__content {
  background: rgba(0, 149, 255, 0.1);
}

::v-deep .tableInput {
  display: inline;
}

::v-deep .tableInput .el-input__inner {
  padding: 0 5px;
  text-align: center;
  width: 30px;
}
</style>
